package com.xingxuecn.demos.common;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * 扩展Spring的JdbcTemplate
 *
 * @author Kris at 2018/9/27 16:16
 */
public class MyJdbcTemplate<T> extends JdbcTemplate {

    /**
     * 查询，并且自动映射到DTO
     *
     * @param tClass 映射的目标类型
     * @param args   jdbc参数
     */
    public <T> List<T> queryForListMapper(String sql, Class<T> tClass, Object... args) {
        return super.query(sql, args, RowMapperFactory.getRowMapper(tClass));
    }


    /**
     * 插入，返回自增长主键
     * @param sql
     * @param args
     * @return
     */
    public Number insert(final String sql, final Object... args) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        int rows = super.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement preparedStatement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                if (args != null) {
                    for (int i = 0; i < args.length; i++) {
                        preparedStatement.setObject(i + 1, args[i]);
                    }
                }
                return preparedStatement;
            }
        }, keyHolder);
        return keyHolder.getKey();
    }
}
